dongwu3596 2015-08-06 13:15
浏览 59

Android示例无法连接到网络服务器

i am testing to connect my android app to a webserver, i used a samle code from the internet. i think the code from the internet will be correct but it wont connect to my server.Maybe some one have an idea. I am using a server at 000webhost.com

First here is my MainActivity.java

enter code here

package com.example.david.mysqlexample;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

 public class MainActivity extends Activity {

    private EditText usernameField,passwordField;
    private TextView status,role,method, tvServer;
    String http_url = "http://sql13.000webhost.com/";
    //String http_url = "www.google.de/";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        usernameField = (EditText)findViewById(R.id.editText1);
        passwordField = (EditText)findViewById(R.id.editText2);

        status = (TextView)findViewById(R.id.textView6);
        role = (TextView)findViewById(R.id.textView7);
        method = (TextView)findViewById(R.id.textView9);
        tvServer = (TextView) findViewById(R.id.tvServer);

        try {

            URL url = new URL(http_url);
            executeReq(url);

            tvServer.setText("HttpURLConnection Available");
        }
        catch(Exception e) {

           tvServer.setText(new String("Connection Failed") +e.getMessage);
        }

    }

private void executeReq(URL url) throws IOException {
    // TODO Auto-generated method stub

    HttpURLConnection con = (HttpURLConnection) url.openConnection();
    con.setReadTimeout(3000);
    con.setConnectTimeout(3500);
    con.setRequestMethod("GET");
    con.setDoInput(true);

    // Connect
    con.connect();
}

    /*
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
    */

    public void login(View view){
        String username = usernameField.getText().toString();
        String password = passwordField.getText().toString();
        method.setText("Get Method");
        new SigninActivity(this,status,role,0).execute(username,password);

    }

    public void loginPost(View view){
        String username = usernameField.getText().toString();
        String password = passwordField.getText().toString();
        method.setText("Post Method");


        new SigninActivity(this,status,role,1).execute(username,password);
    }
}

The Exception Error is : Unkown protocol The Code for my SigninActivity.java is here:

package com.example.david.mysqlexample;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.content.Context;
import android.os.AsyncTask;
import android.widget.TextView;

public class SigninActivity  extends AsyncTask<String,Void,String>{
private TextView statusField,roleField;
private Context context;
private int byGetOrPost = 0;

//flag 0 means get and 1 means post.(By default it is get.)
public SigninActivity(Context context,TextView statusField,TextView roleField,int flag) {
    this.context = context;
    this.statusField = statusField;
    this.roleField = roleField;
    byGetOrPost = flag;
}

protected void onPreExecute(){

}

@Override
protected String doInBackground(String... arg0) {
    if(byGetOrPost == 0){ //means by Get Method

        try{
            String username = (String)arg0[0];
            String password = (String)arg0[1];
            String link = "http://sql13.000webhost.com/test3.php?username="+username+"& password="+password;

            URL url = new URL(link);
            HttpClient client = new DefaultHttpClient();
            HttpGet request = new HttpGet();
            request.setURI(new URI(link));
            HttpResponse response = client.execute(request);
            BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

            StringBuffer sb = new StringBuffer("");
            String line="";

            while ((line = in.readLine()) != null) {
                sb.append(line);
                break;
            }
            in.close();
            return sb.toString();
        }

        catch(Exception e){
            return new String("Exception: " + e.getMessage());
        }
    }
    else{
        try{
            String username = (String)arg0[0];
            String password = (String)arg0[1];

            String link="http://sql13.000webhost.com/test3.php";
            String data  = URLEncoder.encode("username", "UTF-8") + "=" + URLEncoder.encode(username, "UTF-8");
            data += "&" + URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(password, "UTF-8");

            URL url = new URL(link);
            URLConnection conn = url.openConnection();

            conn.setDoOutput(true);
            OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());

            wr.write( data );
            wr.flush();

            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));

            StringBuilder sb = new StringBuilder();
            String line = null;

            // Read Server Response
            while((line = reader.readLine()) != null)
            {
                sb.append(line);
                break;
            }
            return sb.toString();
        }
        catch(Exception e){
            return new String("Exception: " + e.getMessage());
        }
    }
}

@Override
protected void onPostExecute(String result){
    this.statusField.setText("Login Successful");
    this.roleField.setText(result);
}

}

I dont know if it helps some one here i have the php code:

<?php             $con=mysqli_connect("mysql13.000webhost.com","a1452134_kaeptenlook","david94","a1452134_User");

if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$username = $_POST['username'];
$password = $_POST['password'];
$result = mysqli_query($con,"SELECT Role FROM Tabel where 
Username='$username' and Password='$password'");


$row = mysqli_fetch_array($result);
$data = $row[0];

if($data){
echo $data;
}
mysqli_close($con);
?>

I have the internet permission in my ManifestFile. In the onCreate Methode and executeReq i check for the Connection but this fails. I hope you guys can help me.

  • 写回答

2条回答 默认 最新

  • dpowt82802 2015-08-06 13:22
    关注

    Possibly you have have not provided permission to your app

    <uses-permission android:name="android.permission.INTERNET" />
    

    in your AndroidManifest.xml

    评论

报告相同问题?

悬赏问题

  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来