1、get 用 IntentService请求
public class MyIntentService extends IntentService {
public MyIntentService() {
super("MyIntentService");
}
@Override
protected void onHandleIntent(Intent intent) {
HttpUtil.getInstance().get();
public void get(){
try {
URL url = new URL("http://43.143.146.165:7777/foods/getFoods?currentPage=1&pageSize=12");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("GET");
httpURLConnection.setConnectTimeout(10*1000);
httpURLConnection.setReadTimeout(10*1000);
httpURLConnection.connect();
if(httpURLConnection.getResponseCode()==200){
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();
String str="";
while ((str= bufferedReader.readLine())!=null){
stringBuilder.append(str);
}
Log.d("TAG", "zzz"+stringBuilder.toString());
}
} catch (MalformedURLException e) {
throw new RuntimeException(e);
} catch (ProtocolException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
2、用POST 线程请求
public class MyThread2 extends Thread{
String name;
public MyThread2(String name) {
this.name = name;
Log.i("MyThread2", "MyThread2");
}
@Override
public void run() {
super.run();
HttpUtil.getInstance().post(name);
}
}
public void post(String name){
try {
URL url = new URL(name);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setConnectTimeout(10*1000);
connection.setReadTimeout(10*1000);
connection.setDoOutput(true);
connection.setDoInput(true);
String params="pageSize=10¤tPage=1";
OutputStream outputStream = connection.getOutputStream();
outputStream.write(params.getBytes());
outputStream.flush();
if (connection.getResponseCode()==200){
InputStream inputStream = connection.getInputStream();
byte[] bytes = new byte[1024];
int len=0;
StringBuilder stringBuilder = new StringBuilder();
while ((len=inputStream.read(bytes))!=-1){
stringBuilder.append(new String(bytes,0,len));
}
String s = stringBuilder.toString();
Log.d("--zcx","run:"+s);
}
} catch (MalformedURLException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
}