下面是代码
GET
public class UrlHttpGet {
public String getHttp(String path){
String text=null;
try {
URL url=new URL(path);
HttpURLConnection connection=(HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
connection.connect();
if(connection.getResponseCode()==HttpURLConnection.HTTP_OK) {
InputStream in=connection.getInputStream();
BufferedReader br=new BufferedReader(new InputStreamReader(in,"UTF-8"));
String s=null;
StringBuffer sb=new StringBuffer();
while((s=br.readLine())!=null) {
sb.append(s);
}
br.close();
text=sb.toString();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return text;
}
}
POST
public class UrlHttpPost {
public String gerPost(String path,String body){
String text=null;
try {
URL url=new URL(path);
HttpURLConnection connetcion =(HttpURLConnection) url.openConnection();
connetcion.setRequestMethod("POST");
connetcion.setDoOutput(true);
connetcion.setDoInput(true);
connetcion.setUseCaches(false);
connetcion.setRequestProperty("Content-type", "application/json;charset=utf-8");
connetcion.connect();
StringBuffer sb=new StringBuffer();
OutputStream bw=connetcion.getOutputStream();
bw.write(body.getBytes());
bw.close();
String t=null;
int a=connetcion.getResponseCode();
if(a==HttpURLConnection.HTTP_OK) {
BufferedReader br=new BufferedReader(new InputStreamReader(connetcion.getInputStream(),"utf-8"));
while((t=br.readLine())!=null) {
sb.append(t);
}
text=sb.toString();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return text;
}
}
PUT
public class UrlHttpPut {
public String setPut(String path,String body) {
String text=null;
try {
URL url=new URL(path);
HttpURLConnection connection=(HttpURLConnection) url.openConnection();
connection.setRequestMethod("PUT");
connection.setRequestProperty("Content-type", "application/JSON;charset=utf-8");
connection.setRequestProperty("Authorization", "TOKEN");
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setReadTimeout(5000);
connection.connect();
OutputStream os=connection.getOutputStream();
os.write(body.getBytes());
os.flush();
os.close();
String str=null;
StringBuffer sb=new StringBuffer();
if(connection.getResponseCode()==HttpURLConnection.HTTP_OK) {
BufferedReader br=new BufferedReader(new InputStreamReader(connection.getInputStream(),"utf-8"));
while((str=br.readLine())!=null) {
sb.append(str);
}
br.close();
}
text=sb.toString();
System.out.println(text);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return text;
}
}
|