Java 通过android应用程序连接到PHP脚本
这是我目前掌握的代码Java 通过android应用程序连接到PHP脚本,java,php,android,Java,Php,Android,这是我目前掌握的代码 public void postData(String toPost) { // Create a new HttpClient and Post Header HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("http://www.mywebsite.com/dev/reverser.php"); //This is the
public void postData(String toPost) {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.mywebsite.com/dev/reverser.php");
//This is the data to send
String MyName = toPost; //any data to send
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("action", MyName));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String response = httpclient.execute(httppost, responseHandler);
//This is the response from a php application
String reverseString = response;
Toast.makeText(this, "response" + reverseString, Toast.LENGTH_LONG).show();
} catch (ClientProtocolException e) {
Toast.makeText(this, "CPE response " + e.toString(), Toast.LENGTH_LONG).show();
// TODO Auto-generated catch block
} catch (IOException e) {
Toast.makeText(this, "IOE response " + e.toString(), Toast.LENGTH_LONG).show();
// TODO Auto-generated catch block
}
}//end postData()
尝试打印出异常。 使用此代码打印您的响应。检查响应的状态
HttpResponse response = client.execute(request);
String line;
br = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
while ((line = br.readLine()) != null)
{
sb.append(line + "\n");
}
br.close();
}
catch(Exception e)
{
Toast.makeText(HttpPostActivity.this, "Exception: " + e.toString(), Toast.LENGTH_LONG).show();
}
告诉我们例外情况。那就很容易找出你的问题了
编辑:答复:
您正试图在主线程上执行网络操作。这样做是违法的。创建一个异步任务,即创建一个单独的线程来执行网络操作
在上面的一条评论中,您指出您将获得一个
android.os.NetworkOnMainThreadException
在最新版本的Android中,不允许在主线程上进行联网,因为这会使UI无响应。使用
AsyncTask
()或其他机制将代码移动到另一个线程。根据海报的要求添加作为单独的答案
假设:
a)有一个文本框,用于接受要加载的URL
b)一个按钮,单击该按钮可对获取的URL执行联网操作
实现一个按钮单击侦听器,该侦听器调用以下函数:
private void URL()
{
String url = txtURL.getText().toString();
new URLTask().execute(new String[] { url });
}
private class URLTask extends AsyncTask<String, Void, String>
{
protected String doInBackground(String... urls)
{
BufferedReader br = null;
String url = urls[0];
StringBuffer sb = new StringBuffer("");
try
{
HttpClient client = new DefaultHttpClient();
HttpPost request = new HttpPost();
request.setURI(new URI(url));
List<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("param1", "value of param1"));
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);
request.setEntity(formEntity);
HttpResponse response = client.execute(request);
String line;
br = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
while ((line = br.readLine()) != null)
{
sb.append(line + "\n");
}
br.close();
}
catch(Exception e)
{
Toast.makeText(HttpPostActivity.this, "Exception: " + e.toString(), Toast.LENGTH_LONG).show();
}
finally
{
if (br != null)
{
try
{
br.close();
}
catch(IOException ioe)
{
ioe.printStackTrace();
}
}
}
return(sb.toString());
}
protected void onPostExecute(String result)
{
txtContent.setText(result);
}
private void URL()
{
字符串url=txtURL.getText().toString();
新建URLTask().execute(新字符串[]{url});
}
私有类URLTask扩展了AsyncTask
{
受保护的字符串doInBackground(字符串…URL)
{
BufferedReader br=null;
字符串url=url[0];
StringBuffer sb=新的StringBuffer(“”);
尝试
{
HttpClient=new DefaultHttpClient();
HttpPost请求=新建HttpPost();
setURI(新的URI(url));
List postParameters=new ArrayList();
添加(新的BasicNameValuePair(“param1”,“param1的值”);
UrlEncodedFormEntity formEntity=新的UrlEncodedFormEntity(后参数);
请求。setEntity(formEntity);
HttpResponse response=client.execute(请求);
弦线;
br=新的BufferedReader(新的InputStreamReader(response.getEntity().getContent());
而((line=br.readLine())!=null)
{
sb.追加(第+行“\n”);
}
br.close();
}
捕获(例外e)
{
Toast.makeText(HttpPostActivity.this,“异常:+e.toString(),Toast.LENGTH_LONG).show();
}
最后
{
如果(br!=null)
{
尝试
{
br.close();
}
捕获(ioe异常ioe)
{
ioe.printStackTrace();
}
}
}
使(某人)返回字符串();
}
受保护的void onPostExecute(字符串结果)
{
txtContent.setText(结果);
}
您还需要实现onPostExecute。还有其他API
您为什么不告诉我们您得到的异常的具体情况。您可以使用android调试器来执行此操作。另外,将响应打印为Toast的方式也不正确。AndroidRuntime(15110):java.lang.RuntimeException:无法启动activity ComponentInfo{com.example.connectingtophpandreturningdata/com.example.connectingtophpandreturningdata.MainActivity}:android.os.networkonmainthreadeption我使用了你的代码。我得到了以下异常-android.os.networkonmainthreadeption检查我的更新答案。如果你需要帮助创建异步任务线程。请告诉我Rockstar谢谢你的回答。是的,甚至我已经得出结论,网络操作正在主线程上执行(不知道这是不允许的)。无论如何,我会很快查看你给我的链接。同时,你能不能通过将AsyncTask添加到我上面介绍的代码中,向我展示一下它是如何使用的。那将是最好的!是的。谢谢你的回答。我相信这是NetworkMainThreadException。你建议我如何在代码中实现AsyncTask?你能实现吗你自己把它写进代码中,并把它作为一个答案吗?这样,我可以立即使用它,并且可以给你的答案打1+@AdvaitS我已经添加了一个到开发者网站文档的链接,介绍如何使用AsyncTasks。rockstar链接到的SO问题中还有一个例子。基本上,你创建了一个扩展
AsyncTask ,将您的网络代码放入doInBackground
方法,返回结果,然后在onPostExecute
方法中更新UI。然后您只需创建一个实例并调用execute
。谢谢您的回答!
private void URL()
{
String url = txtURL.getText().toString();
new URLTask().execute(new String[] { url });
}
private class URLTask extends AsyncTask<String, Void, String>
{
protected String doInBackground(String... urls)
{
BufferedReader br = null;
String url = urls[0];
StringBuffer sb = new StringBuffer("");
try
{
HttpClient client = new DefaultHttpClient();
HttpPost request = new HttpPost();
request.setURI(new URI(url));
List<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("param1", "value of param1"));
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);
request.setEntity(formEntity);
HttpResponse response = client.execute(request);
String line;
br = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
while ((line = br.readLine()) != null)
{
sb.append(line + "\n");
}
br.close();
}
catch(Exception e)
{
Toast.makeText(HttpPostActivity.this, "Exception: " + e.toString(), Toast.LENGTH_LONG).show();
}
finally
{
if (br != null)
{
try
{
br.close();
}
catch(IOException ioe)
{
ioe.printStackTrace();
}
}
}
return(sb.toString());
}
protected void onPostExecute(String result)
{
txtContent.setText(result);
}