我是Android的新人。我正在尝试连接MySQL以获取来自android应用程序的商店值。但我在连接到我的服务器时遇到问题。请帮助我......?。
错误:org.apache.http.NoHttpResponseException:目标服务器无法响应 这是代码:
MainActivity.java
package com.example.easyeop;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
public class MainActivity extends Activity implements OnClickListener,OnItemSelectedListener{
EditText ename;
String date;
Spinner category;
Spinner product;
Spinner merchant;
EditText qty;
Spinner unit;
EditText rate;
TextView vals;
double value;
JSONParser jsonParser = new JSONParser();
private Button mSubmit;
private Button mCancel;
private String spinner_category[];
private ProgressDialog pDialog;
private static String registerURL = "http://223.185.164.105:8080/mywebs/index.php";
private static String register_tag = "register";
private static final String TAG_SUCCESS = "success";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ename=(EditText) findViewById(R.id.eename);
category=(Spinner) findViewById(R.id.spinner1);
product=(Spinner)findViewById(R.id.spinner2);
merchant=(Spinner)findViewById(R.id.spinner3);
qty=(EditText)findViewById(R.id.eqty);
unit=(Spinner)findViewById(R.id.spinner4);
rate=(EditText)findViewById(R.id.erate);
vals=(TextView) findViewById(R.id.dvalue);
mSubmit = (Button) findViewById(R.id.submit);
mSubmit.setOnClickListener(this);
mCancel = (Button) findViewById(R.id.cancel);
mCancel.setOnClickListener(this);
spinner_category=new String[2];
spinner_category[0]="Category11";
spinner_category[1]="Category22";
ArrayAdapter<String> spinnerCategory = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, spinner_category);
category.setAdapter(spinnerCategory);
category.setOnItemSelectedListener(this);
ArrayAdapter<String> spinnerProduct = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, new String[] {
new String("Product1"), new String("Product2") });
product.setAdapter(spinnerProduct);
product.setOnItemSelectedListener(this);
ArrayAdapter<String> spinnerMerchant = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, new String[] {
new String("Ajith"), new String("Piyush") });
merchant.setAdapter(spinnerMerchant);
merchant.setOnItemSelectedListener(this);
ArrayAdapter<String> spinnerUnit = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, new String[] {
new String("KG"), new String("Tons") });
unit.setAdapter(spinnerUnit);
unit.setOnItemSelectedListener(this);
}
class saveNewData extends AsyncTask<String, String, String>{
@Override
protected void onPreExecute(){
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Saving Details...!");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
@Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
System.out.println("Do In Background...");
String name=ename.getText().toString();
String cat=category.getSelectedItem().toString();
String prd=product.getSelectedItem().toString();
String mer=merchant.getSelectedItem().toString();
String qt=qty.getText().toString();
String uni=unit.getSelectedItem().toString();
String rat=rate.getText().toString();
Date d=new Date();
SimpleDateFormat format=new SimpleDateFormat("dd-MM-yyyy");
date=format.format(d);
// Building Parameters
System.out.println("bfr building params");
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("tag", register_tag));
params.add(new BasicNameValuePair("name", name));
params.add(new BasicNameValuePair("tdate", date));
params.add(new BasicNameValuePair("category", cat));
params.add(new BasicNameValuePair("product", prd));
params.add(new BasicNameValuePair("merchant", mer));
params.add(new BasicNameValuePair("qty", qt));
params.add(new BasicNameValuePair("unit", uni));
params.add(new BasicNameValuePair("rate", rat));
System.out.println("aftr building params");
// getting JSON Object
// Note that save details url accepts POST method
System.out.println("save details url accepts POST method...");
JSONObject json = jsonParser.makeHttpRequest(registerURL,
"POST", params);
System.out.println("aftr save details url accepts POST method...");
// check log cat for response
Log.d("Create Response", json.toString());
System.out.println("create response...");
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully saved details
System.out.println("successfully saved...");
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
// closing this screen
finish();
} else {
// failed to save details
System.out.println("failed to save details...");
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.cancel:
Intent i = new Intent(getBaseContext(), MainActivity.class);
startActivity(i);
// finish();
break;
case R.id.submit:
// TODO Auto-generated method stub
// creating new product in background thread
System.out.println("Inside Submit");
new saveNewData().execute();
break;
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
JSONParser.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET method
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
System.out.println("method=post");
// HttpParams httpParameters=new BasicHttpParams();
// int timeoutConnection = 3000;
// HttpConnectionParams.setConnectionTimeout(httpParameters,timeoutConnection);
// int timeoutSocket = 5000;
// HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
System.out.println("UnsupportedEncodingException..."+e);
e.printStackTrace();
} catch (ClientProtocolException e) {
System.out.println("ClientProtocolException..."+e);
e.printStackTrace();
} catch (IOException e) {
System.out.println("IOException..."+e);
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
logcat的:
12-31 11:44:47.718: D/ddm-heap(220): Got feature list request
12-31 11:48:15.258: W/KeyCharacterMap(220): No keyboard for id 0
12-31 11:48:15.258: W/KeyCharacterMap(220): Using default keymap: /system/usr/keychars/qwerty.kcm.bin
12-31 11:48:29.128: I/System.out(220): Inside Submit
12-31 11:48:29.259: I/System.out(220): Do In Background...
12-31 11:48:29.259: I/System.out(220): name :hfdw
12-31 11:48:29.259: I/System.out(220): category :Category11
12-31 11:48:29.259: I/System.out(220): product :Product1
12-31 11:48:29.259: I/System.out(220): merchant :Ajith
12-31 11:48:29.259: I/System.out(220): qty :445
12-31 11:48:29.259: I/System.out(220): unit :KG
12-31 11:48:29.259: I/System.out(220): rate :67
12-31 11:48:30.009: I/System.out(220): date :31-12-2012
12-31 11:48:30.020: I/System.out(220): bfr building params
12-31 11:48:30.239: I/System.out(220): aftr building params
12-31 11:48:30.309: I/System.out(220): save details url accepts POST method...
12-31 11:48:30.318: I/System.out(220): method=post
12-31 11:48:30.580: I/System.out(220): send params
12-31 11:48:30.828: D/dalvikvm(220): GC freed 3512 objects / 211920 bytes in 139ms
12-31 11:48:35.178: D/dalvikvm(220): GC freed 316 objects / 194992 bytes in 114ms
12-31 11:48:39.218: I/System.out(220): IOException...org.apache.http.NoHttpResponseException: The target server failed to respond
12-31 11:48:39.228: E/IO Exception(220): Errorrr
12-31 11:48:39.228: W/System.err(220): org.apache.http.NoHttpResponseException: The target server failed to respond
12-31 11:48:39.290: W/System.err(220): at org.apache.http.impl.conn.DefaultResponseParser.parseHead(DefaultResponseParser.java:85)
12-31 11:48:39.298: W/System.err(220): at org.apache.http.impl.io.AbstractMessageParser.parse(AbstractMessageParser.java:174)
12-31 11:48:39.326: W/System.err(220): at org.apache.http.impl.AbstractHttpClientConnection.receiveResponseHeader(AbstractHttpClientConnection.java:179)
12-31 11:48:39.338: W/System.err(220): at org.apache.http.impl.conn.DefaultClientConnection.receiveResponseHeader(DefaultClientConnection.java:235)
12-31 11:48:39.348: W/System.err(220): at org.apache.http.impl.conn.AbstractClientConnAdapter.receiveResponseHeader(AbstractClientConnAdapter.java:259)
12-31 11:48:39.348: W/System.err(220): at org.apache.http.protocol.HttpRequestExecutor.doReceiveResponse(HttpRequestExecutor.java:279)
12-31 11:48:39.370: W/System.err(220): at org.apache.http.protocol.HttpRequestExecutor.execute(HttpRequestExecutor.java:121)
12-31 11:48:39.370: W/System.err(220): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:410)
12-31 11:48:39.370: W/System.err(220): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
12-31 11:48:39.370: W/System.err(220): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
12-31 11:48:39.370: W/System.err(220): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
12-31 11:48:39.370: W/System.err(220): at com.example.easyeop1.JSONParser.makeHttpRequest(JSONParser.java:57)
12-31 11:48:39.370: W/System.err(220): at com.example.easyeop1.MainActivity$saveNewData.doInBackground(MainActivity.java:159)
12-31 11:48:39.370: W/System.err(220): at com.example.easyeop1.MainActivity$saveNewData.doInBackground(MainActivity.java:1)
12-31 11:48:39.370: W/System.err(220): at android.os.AsyncTask$2.call(AsyncTask.java:185)
12-31 11:48:39.370: W/System.err(220): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
12-31 11:48:39.370: W/System.err(220): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
12-31 11:48:39.370: W/System.err(220): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1068)
12-31 11:48:39.378: W/System.err(220): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:561)
12-31 11:48:39.378: W/System.err(220): at java.lang.Thread.run(Thread.java:1096)
12-31 11:48:39.378: E/Buffer Error(220): Error converting result java.lang.NullPointerException
12-31 11:48:39.388: E/JSON Parser(220): Error parsing data org.json.JSONException: A JSONObject text must begin with '{' at character 0 of
12-31 11:48:39.398: I/System.out(220): aftr save details url accepts POST method...
12-31 11:48:39.431: W/dalvikvm(220): threadid=17: thread exiting with uncaught exception (group=0x4001b188)
12-31 11:48:39.439: E/AndroidRuntime(220): Uncaught handler: thread AsyncTask #1 exiting due to uncaught exception
12-31 11:48:39.459: E/AndroidRuntime(220): java.lang.RuntimeException: An error occured while executing doInBackground()
12-31 11:48:39.459: E/AndroidRuntime(220): at android.os.AsyncTask$3.done(AsyncTask.java:200)
12-31 11:48:39.459: E/AndroidRuntime(220): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
12-31 11:48:39.459: E/AndroidRuntime(220): at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
12-31 11:48:39.459: E/AndroidRuntime(220): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
12-31 11:48:39.459: E/AndroidRuntime(220): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
12-31 11:48:39.459: E/AndroidRuntime(220): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1068)
12-31 11:48:39.459: E/AndroidRuntime(220): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:561)
12-31 11:48:39.459: E/AndroidRuntime(220): at java.lang.Thread.run(Thread.java:1096)
12-31 11:48:39.459: E/AndroidRuntime(220): Caused by: java.lang.NullPointerException
12-31 11:48:39.459: E/AndroidRuntime(220): at com.example.easyeop1.MainActivity$saveNewData.doInBackground(MainActivity.java:163)
12-31 11:48:39.459: E/AndroidRuntime(220): at com.example.easyeop1.MainActivity$saveNewData.doInBackground(MainActivity.java:1)
12-31 11:48:39.459: E/AndroidRuntime(220): at android.os.AsyncTask$2.call(AsyncTask.java:185)
12-31 11:48:39.459: E/AndroidRuntime(220): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
12-31 11:48:39.459: E/AndroidRuntime(220): ... 4 more
12-31 11:48:39.489: I/dalvikvm(220): threadid=7: reacting to signal 3
12-31 11:48:39.540: I/dalvikvm(220): Wrote stack trace to '/data/anr/traces.txt'
12-31 11:48:44.939: I/Process(220): Sending signal. PID: 220 SIG: 9
答案 0 :(得分:2)
我遇到了同样的问题。它似乎与ICS之前的操作系统版本中的错误相关 - 或者在我的情况下。你在运行哪个Android版本?
这段代码为我解决了这个问题(参考:http://code.google.com/p/android/issues/detail?id=13117#c14)
private void workAroundReverseDnsBugInHoneycombAndEarlier(HttpClient client) {
// Android had a bug where HTTPS made reverse DNS lookups (fixed in Ice Cream Sandwich)
// http://code.google.com/p/android/issues/detail?id=13117
SocketFactory socketFactory = new LayeredSocketFactory() {
SSLSocketFactory delegate = SSLSocketFactory.getSocketFactory();
@Override public Socket createSocket() throws IOException {
return delegate.createSocket();
}
@Override public Socket connectSocket(Socket sock, String host, int port,
InetAddress localAddress, int localPort, HttpParams params) throws IOException {
return delegate.connectSocket(sock, host, port, localAddress, localPort, params);
}
@Override public boolean isSecure(Socket sock) throws IllegalArgumentException {
return delegate.isSecure(sock);
}
@Override public Socket createSocket(Socket socket, String host, int port,
boolean autoClose) throws IOException {
injectHostname(socket, host);
return delegate.createSocket(socket, host, port, autoClose);
}
private void injectHostname(Socket socket, String host) {
try {
Field field = InetAddress.class.getDeclaredField("hostName");
field.setAccessible(true);
field.set(socket.getInetAddress(), host);
} catch (Exception ignored) {
}
}
};
client.getConnectionManager().getSchemeRegistry()
.register(new Scheme("https", socketFactory, 443));
}
答案 1 :(得分:0)
错误是NoHttpResponseException
的事实,我猜这个错误是由于网络问题或服务器过载造成的!
答案 2 :(得分:0)
尝试使用https://code.google.com/p/httpclientandroidlib/替换android 4.0(ICS)之前的httpclient,我使用这个jar修复了这个bug。