您的位置:首页 > 编程语言 > Java开发

java URL以及UrlConnection使用解析

2012-03-19 09:39 495 查看
/****************************************************************/
//>java URL和Connection使用解析
/****************************************************************/

/****************************************************************/
>0.示例代码
public static void main(String[] args) {
try {
//要想struts2的表单值天器自动填充就必须使用伪URL传参不管是使用get还是POST
//?path=c:/test.xml&test=2012
String spec = "http://localhost:8080/testRRC/solrIndex/testAction!test";
URL url = new URL(spec);
System.out.println(url);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setInstanceFollowRedirects(true);
conn.setRequestProperty("content-type", "text/html");

conn.connect();// 握手
OutputStream os = conn.getOutputStream();// 拿到输出流
// os.write("?path=c:/test.xml&test=2012".getBytes("utf-8"));
PrintWriter out = new PrintWriter(os);
out.print("?path=c:/test.xml&test=2012");

out.flush();
os.flush();
out.close();
os.close();

InputStream is = conn.getInputStream();//拿到输入流
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String s = br.readLine();
System.out.println(s);

br.close();
isr.close();
is.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/****************************************************************/

/****************************************************************/
>1.不能在URL为传参的时候用的方式(示例代码)
/**
* 读取配置文件(schema.xml,solrconfig.xml内容)
* @param json
* @return
*/
public JSONObject editSchema(JSONObject json){
solrLog.info("query data="+json);
JSONObject object=new JSONObject();
boolean flag=true;
String error="";
URL url;
try {
JSONObject shardJSON=new JSONObject(json.getString("shard"));
url = new URL("http://localhost:8080/patIndexManager/schemaEdit.action");
HttpURLConnection conn=(HttpURLConnection)url.openConnection();
conn.setRequestMethod("POST");

conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("Charsert", "UTF-8");
conn.setInstanceFollowRedirects(true);
conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
conn.connect();
//注意这里需要用缓存写入器进行写入不然到另外一端收不到
//BufferedWriter out = new BufferedWriter(new OutputStreamWriter(
//conn.getOutputStream(), "utf-8"));
//out.write("data="+json);
out.flush();
out.close();

InputStream is=conn.getInputStream();
InputStreamReader reader=new InputStreamReader(is,"utf-8");
String jsonStr="";
int r=0;
while((r=reader.read())!=-1){
jsonStr+=(char)r;
}
object.put("result",jsonStr);
is.close();
reader.close();
}catch (Exception e){
flag=false;
solrLog.error("IOException",e);
error="连接服务器失败";
}
try {
object.put("success", flag);
object.put("error", error);
} catch (JSONException e){
}
return object;
}
/****************************************************************/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: