我有這個代碼的問題,我必須做一個連接到一個php文件的帖子。我必須插入一個線程嗎?如果是,爲什麼?哪裏?http post android不返回響應字符串
public class Login extends Activity {
public String RispostaLogin;
public String response,responseBody;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Button pulsante = (Button) findViewById(R.id.button2);
pulsante.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d("myapp", "cliccato");
sendPostRequest();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_login, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void sendPostRequest()
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("https://api.uniparthenope.it/user/radius/auth");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("user", "user"));
nameValuePairs.add(new BasicNameValuePair("passw", "pass"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
responseBody=EntityUtils.toString(response.getEntity());
Log.d("myapp", responseBody);
} catch (ClientProtocolException e1) {
e1.printStackTrace();
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
試試這個教程 http://hmkcode.com/android-internet-連接使用http-get-httpclient/ – Hasan 2014-12-07 18:31:41
可能的重複[android.os.NetworkOnMainThreadException](http://stackoverflow.com/questions/6343166/android-os-networkonmainthreadexception) – 323go 2014-12-07 18:32:34
*如果*你記得添加互聯網權限,你肯定會崩潰'NetworkOnMainThreadException.'查看鏈接的問題。 – 323go 2014-12-07 18:33:21