gpt4 book ai didi

android - 如何在 Android 应用程序中发送 http 请求以访问 REST API

转载 作者:IT老高 更新时间:2023-10-28 23:11:48 29 4
gpt4 key购买 nike

谁能解决我的问题。我想在android中发送一个http请求来访问REST API(PHP)..

谢谢

最佳答案

http://breaking-catch22.com/?p=12

public class AndroidApp extends Activity {  

String URL = "http://the/url/here";
String result = "";
String deviceId = "xxxxx" ;
final String tag = "Your Logcat tag: ";

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

final EditText txtSearch = (EditText)findViewById(R.id.txtSearch);
txtSearch.setOnClickListener(new EditText.OnClickListener(){
public void onClick(View v){txtSearch.setText("");}
});

final Button btnSearch = (Button)findViewById(R.id.btnSearch);
btnSearch.setOnClickListener(new Button.OnClickListener(){
public void onClick(View v) {
String query = txtSearch.getText().toString();
callWebService(query);

}
});

} // end onCreate()

public void callWebService(String q){
HttpClient httpclient = new DefaultHttpClient();
HttpGet request = new HttpGet(URL + q);
request.addHeader("deviceId", deviceId);
ResponseHandler<string> handler = new BasicResponseHandler();
try {
result = httpclient.execute(request, handler);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
httpclient.getConnectionManager().shutdown();
Log.i(tag, result);
} // end callWebService()
}

关于android - 如何在 Android 应用程序中发送 http 请求以访问 REST API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5769549/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com