httpResponse = httpClient.execute(httpGet)之后的Android代码无法运行

时间:2016-05-23 10:14:37

标签: java android c http

我正在开发一个Android应用程序,它将向服务器发送HTTP请求,服务器将回复任何字符串。我对HTTP很新。我的服务器应用程序是用C编程的(我不确定C会不会服务器是否为HTTP工作,但它适用于套接字通信) 当我从Android设备进行HTTP调用时,我在服务器上获得连接请求,并且还接收一些数据字节,其中也包含Android发送的数据,但是android软件挂起

httpResponse =httpClient.execute(httpGet);

它甚至不会抛出异常。我已经在一个单独的线程中编写了HTTP代码。

这是我的Android端代码:

public class MainActivity extends Activity {

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


  final Button btn1 = (Button)findViewById(R.id.button1); 

   btn1.setOnClickListener(new View.OnClickListener() {
       @Override
       public void onClick(View v) {


           Threading thrd = new Threading();
           thrd.start();

       }

   });  }

@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;
}

@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();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}}

这是Thread类:

public class threading extends Thread {

    public void run(){
        String url; 
        int method;
        InputStream is = null;
        List<NameValuePair> params = new ArrayList<NameValuePair>(); 



        try {

        url = "HTTP://192.168.0.32:7024" ;
        params.add(new BasicNameValuePair("network", "w"));
        params.add(new BasicNameValuePair("imei", "465465464654654564"));
       DefaultHttpClient httpClient = new DefaultHttpClient();
       HttpEntity httpEntity = null;
       HttpResponse httpResponse = null; 

        if (params != null) {
         String paramString = URLEncodedUtils.format(params, "UTF-8");
         url += "?" + paramString;
        }
        HttpGet httpGet = new HttpGet(url);
       httpResponse =httpClient.execute(httpGet);


       httpEntity = httpResponse.getEntity();
       is = httpEntity.getContent();

      } catch (UnsupportedEncodingException e) {
       e.printStackTrace();  
      } catch (ClientProtocolException e) {
       e.printStackTrace();   
      } catch (IOException e) {
       e.printStackTrace();
      }

      String response;
    try {
       BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8);
       StringBuilder sb = new StringBuilder();
       String line = null;
       while ((line = reader.readLine()) != null) {
        sb.append(line + "\n");
       }
       is.close();
       response = sb.toString();
      } catch (Exception e) {
       Log.e("Buffer Error", "Error: " + e.toString());

      }


    }}

这是C服务器应用程序:

MAIN.C

void main(int argc, char** argv){

    int sock_desc = 0;
    int connfd = 0;
    int conn_desc = 0;
    int clntSock; 
    struct sockaddr_in serv_addr;
    struct sockaddr_in echoClntAddr;  
    int rc;
    struct timeval timeout; 



    active_clients_count = 0;
    sock_desc = socket(AF_INET, SOCK_STREAM, 0); 
    if(sock_desc < 0 )
        dieWithError("Unable to open Socket\n");

    memset(&serv_addr,0,sizeof(serv_addr)); 
    serv_addr.sin_family = AF_INET ;
    serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
    serv_addr.sin_port = htons(7024);
    if(bind(sock_desc, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) 
        dieWithError("bind failed\n");

    if(listen(sock_desc,MAX_CONNECTIONS) < 0)
        dieWithError("listen failed\n");  

    clntSock = sizeof(struct sockaddr);
    while(1){
        connfd = accept(sock_desc, (struct sockaddr *)&echoClntAddr, (socklen_t*)&clntSock);
        if(connfd > 0){  
            conn_desc = connfd;
            puts("Connection accepted");
            struct sockaddr_in addr;
            socklen_t addr_size = sizeof(struct sockaddr_in);
            int res = getpeername(connfd, (struct sockaddr *)&addr, &addr_size);
            char clientip[20] ;
            strcpy(clientip, inet_ntoa(addr.sin_addr));
            printf("Client IP is %s\n",clientip);
            if(pthread_create( &thr, NULL, connection_handler, (void*)&conn_desc) < 0){
                perror("could not create thread");
            }

            puts("Handler assigned");
        }       
    }

}

void dieWithError(char *errormsg){ 
    printf("%s", errormsg);    
}

这是connectionHandler.C

void *connection_handler(void* socket_desc){

    int sock = *(int*)socket_desc;
    int read_size,send_size;  
    char client_message[40006];
    int rc = 0;
    char recvBuff[3100];

    active_clients_count ++; 
    memset(&t_data[sock].sock_id, 0, sizeof(t_data[1])) ;  

    read_size = recv(sock, client_message, sizeof(client_message), 0); 
    recvBuff[0] = 'H';
    recvBuff[1] = 'E';
    recvBuff[2] = 'L';
    recvBuff[3] = 'L';
    recvBuff[4] = 'o';
    send_size =  send(sock, recvBuff, 5, 0) ;}

我的C代码是否适用于HTTP请求,或者我需要用其他语言编写新代码才能运行。

0 个答案:

没有答案