与https://xxx.x.x.x的连接被拒绝

时间:2014-03-11 05:55:57

标签: java php android mysql

我正在尝试使用php脚本和JSON响应检索存储在Mysql数据库中的数据。但是当我运行程序时,我得到输出为无法连接到数据库。

MainActivity.java

public class MainActivity extends Activity {
TextView resultView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    StrictMode.enableDefaults();
    resultView = (TextView) findViewById(R.id.result);
    getData();
}

public void getData() {
    String result = " ";
    InputStream isr = null;
    try {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("https://192.168.x.xx/sheetal/getdata.php");
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        isr = entity.getContent();

    } catch (Exception e) {
        Log.e("log_tag", "Error in http connection" + e.toString());
        resultView.setText("Could'nt connect to database");
    }
    //convert response to string
    try {

        BufferedReader reader = new BufferedReader(new InputStreamReader(isr, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        isr.close();
        result = sb.toString();
    } catch (Exception e) {
        Log.e("log_tag", "Error converting result" + e.toString());
    }

    //parse json data
    try {
        String s = "";
        JSONArray jArray = new JSONArray(result);

        for (int i = 0; i < jArray.length(); i++) {
            JSONObject json = jArray.getJSONObject(i);
            s = s +
                "Name: " + json.getString("Firstname") + " " + json.getString("Lastname") + "\n" +
                "Age: " + json.getInt("Age") + "\n" +
                "Mobile Using: " + json.getString("Product") + "\n\n";

        }

        resultView.setText(s);
    } catch (Exception e) {
        Log.e("log-teg", "Error Parsing Data" + e.toString());
    }
   }
}

这是我的php文件getdata.php

<?php
$con = mysql_connect("localhost", "root", "");

if (!$con)
{
die('Could not Connect:' . mysql_error());
}

mysql_select_db("test1", $con);
$result = mysql_query("SELECT * FROM customer");

while ($row = mysql_fetch_assoc($result)) $output[] = $row;
print (json_encode($output));
?>

Log-cat错误

  03-11 01:53:37.569: I/Choreographer(1765): Skipped 124 frames!  The application may be doing too much work on its main thread.
  03-11 01:53:45.780: E/log_tag(1765): Error in http connectionjava.lang.IllegalArgumentException: Host name may not be null
  03-11 01:53:45.798: E/log_tag(1765): Error converting resultjava.lang.NullPointerException: lock == null
  03-11 01:53:45.798: E/log-teg(1765): Error Parsing Dataorg.json.JSONException: End of input at character 1 of  
  03-11 01:53:45.968: I/Choreographer(1765): Skipped 120 frames!  The application may be doing too much work on its main thread.
  03-11 01:53:46.298: I/Choreographer(1765): Skipped 45 frames!  The application may be doing too much work on its main thread.

4 个答案:

答案 0 :(得分:1)

调用DefaultHttpClient()方法

是一个问题

当您使用Https时,您需要使用HttpClient,如下所示

创建一个单独的方法,如下所示,

private DefaultHttpClient getHttpClient() 
{
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("https", SSLSocketFactory
            .getSocketFactory(), 443));

    HttpParams params = new BasicHttpParams();
    int timeoutConnection = 30000;
    HttpConnectionParams.setConnectionTimeout(params, timeoutConnection);
    int timeoutSocket = 30000;
    HttpConnectionParams.setSoTimeout(params, timeoutSocket);

    params.setParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS, 30);
    params.setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE,
            new ConnPerRouteBean());
    params.setParameter(HttpProtocolParams.USE_EXPECT_CONTINUE, false);
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);

    ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(
            params, schemeRegistry);
    DefaultHttpClient client = new DefaultHttpClient(cm, params);
    client.setRoutePlanner(new DefaultHttpRoutePlanner(schemeRegistry));
    return (client);
}

将此方法添加到您的代码中并修改以下行

HttpClient httpclient = new DefaultHttpClient();HttpClient httpclient = new DefaultHttpClient();

对此,

HttpClient httpclient = getHttpClient();

答案 1 :(得分:0)

       String myurl="  ";

       URL url = new URL(myurl);
        Log.e(myurl, "Url Executing");
        URLConnection conexion = url.openConnection();
        conexion.setConnectTimeout(100);

        int lenghtOfFile = conexion.getContentLength();


        InputStream input = new BufferedInputStream(url.openStream());

答案 2 :(得分:0)

使用AsyncTask非常简单

  String urls = "http://euroinvo.co.in/gkdb/gkdb";
 new DownloadDb().execute(urls);

class DownloadDb extends AsyncTask<String, String, String> {
@Override
protected String doInBackground(String... aurl) {

    int count;

    String fullpath = "";
    try {

        URL url = new URL(aurl[0]);
        Log.e(aurl[0], "Url Executing");
        URLConnection conexion = url.openConnection();
        conexion.setConnectTimeout(100);
        // conexion.connect();

        int lenghtOfFile = conexion.getContentLength();
        Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);
        // Get directory

        InputStream input = new BufferedInputStream(url.openStream());
          BufferedReader reader = new BufferedReader(new     
    InputStreamReader(input,"iso-8859-1"),8);
    StringBuilder sb = new StringBuilder();
    String line = null;
    while((line = reader.readLine())!= null){
        sb.append(line + "\n");
    }
    isr.close();
    result=sb.toString();

    } catch (Exception e) {


       Log.d("error", e.getMessage());

       }
     return fullpath; 
      }

答案 3 :(得分:0)

你的主要步伐更多。因为你可以使用asynctask。这是更简单的方法。

这是asynctask

的指南

AsyncTask

否则你可以通过out asynctask

检查这个

Android-php-json-tutorial