dongyinzheng6572 2016-01-29 21:10
浏览 75

HttpURLConnection上传到php脚本(插入查询)

I'm trying to upload data into my mysql database.

The code below doesn't throw any errors, but when I check the database, the data isn't there.

Can anyone see what I am doing wrong? It doesnt even seem to run the php.

I have a feeling it is a problem with the php code. It used to work with httppost, but recently, the data started to get mixed up, and it would hang. I saw that httppost is depreciated, so am trying to use HttpURLConnection instead.

Here is the java:

public void uploadmydata() throws Exception {

    URL url = new URL("http://www.myurl.co.uk/test5.php");
    urlConnection = (HttpURLConnection) url.openConnection();
    urlConnection.setReadTimeout(10000);
    urlConnection.setConnectTimeout(15000);
    urlConnection.setRequestMethod("POST");
    urlConnection.setDoInput(true);
    urlConnection.setDoOutput(true);

    List<NameValuePair> params = new ArrayList<NameValuePair>(1);

    params.add(new BasicNameValuePair("name", "Joe"));
    params.add(new BasicNameValuePair("surname", "Bloggs"));
    params.add(new BasicNameValuePair("country", "UK"));


    OutputStream os = urlConnection.getOutputStream();
    BufferedWriter writer = new BufferedWriter(
            new OutputStreamWriter(os, "UTF-8"));
    writer.write(getQuery(params));
    writer.flush();
    writer.close();
    os.close();

    urlConnection.connect();


}

private String getQuery(List<NameValuePair> params) throws UnsupportedEncodingException
{
    StringBuilder result = new StringBuilder();
    boolean first = true;

    for (NameValuePair pair : params)
    {
        if (first)
            first = false;
        else
            result.append("&");

        result.append(URLEncoder.encode(pair.getName(), "UTF-8"));
        result.append("=");
        result.append(URLEncoder.encode(pair.getValue(), "UTF-8"));
    }

    return result.toString();
}

and here is my php:

 session_start();


 //CREATE CONNECTION
$con=mysql_connect("00.00.00.00","my_username","password") or die          (mysql_error());

 //CHECK CONNECTION
 if (!$con) { die('Could not connect to MySQL: ' . mysql_error());
 } 

else
//echo 'connected!';

 //SELECT SITE DATABASE

mysql_select_db("my_database", $con);


$name=$_POST['name'];
$surname=$_POST['surname'];
$country=$_POST['country'];


//sql query

mysql_query("insert into myTable (name, surname, country)       values('{$name}','{$surname}','{$country}')");

mysql_close();
  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 如何在scanpy上做差异基因和通路富集?
    • ¥20 关于#硬件工程#的问题,请各位专家解答!
    • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
    • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
    • ¥30 截图中的mathematics程序转换成matlab
    • ¥15 动力学代码报错,维度不匹配
    • ¥15 Power query添加列问题
    • ¥50 Kubernetes&Fission&Eleasticsearch
    • ¥15 報錯:Person is not mapped,如何解決?
    • ¥15 c++头文件不能识别CDialog