核心代码public class HttpActivity extends Activity {
private button mButton1, mButton2;
private textView mTextView1;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mButton1 = (Button) findViewById(R.id.myButton1);
mButton2 = (Button) findViewById(R.id.myButton2);
mTextView1 = (TextView) findViewById(R.id.myTextView1);
mButton1.setOnClicklistener(new Button.OnClickListener() {
public void onClick(View v) {
String uriAPI = "http://www.sina.com";
Httppost httpRequest = new HttpPost(uriAPI);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("str", "post string"));
try {
httpRequest.setEntity(new URLEncodedFormEntity(params,
HTTP.UTF_8));
Httpresponse httpResponse = new DEFAULTHttpClient()
.execute(httpRequest);
if (httpResponse.getStatusLine().getStatusCode() == 200) {
String strResult = EntityUtils.toString(httpResponse
.getEntity());
mTextView1.setText(strResult);
} else {
mTextView1.setText("Error Response: "
httpResponse.getStatusLine().toString());
}
} catch (ClientProtocolException e) {
mTextView1.setText(e.getMessage().toString());
e.printStackTrace();
} catch (IOException e) {
mTextView1.setText(e.getMessage().toString());
e.printStackTrace();
} catch (Exception e) {
mTextView1.setText(e.getMessage().toString());
e.printStackTrace();
}
}
});
mButton2.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
String uriAPI = "http://www.sina.com";
HttpGet httpRequest = new HttpGet(uriAPI);
try {
HttpResponse httpResponse = new DefaultHttpClient()
.execute(httpRequest);
if (httpResponse.getStatusLine().getStatusCode() == 200) {
String strResult = EntityUtils.toString(httpResponse
.getEntity());
strResult = eregi_replace("(\r\n|\r|\n|\n\r)", "",
strResult);
mTextView1.setText(strResult);
} else {
mTextView1.setText("Error Response: "
httpResponse.getStatusLine().toString());
}
} catch (ClientProtocolException e) {
mTextView1.setText(e.getMessage().toString());
e.printStackTrace();
} catch (IOException e) {
mTextView1.setText(e.getMessage().toString());
e.printStackTrace();
} catch (Exception e) {
mTextView1.setText(e.getMessage().toString());
e.printStackTrace();
}
}
});
}
public String eregi_replace(String strFrom, String strTo, String strTarget) {
String strPattern = "(?i)" strFrom;
Pattern p = Pattern.compile(strPattern);
matcher m = p.matcher(strTarget);
if (m.find()) {
return strTarget.replaceAll(strFrom, strTo);
} else {
return strTarget;
}
}
}
来源:搜素材网素材
搜素材网所有素材均为本站用户上传,仅供学习与参考,请勿用于商业用途,如有侵犯您的版权请联系客服服务QQ
本站提供各类html5响应式模板,前端js素材,网站模板,后台模板素材,程序源码素材。
由于技术有限本站不提供安装服务与bug修复,各类源码只提供分享服务,感谢您的理解。
如果对本站有任何意见请点击右侧侧边栏的反馈意见,我们会及时处理。