将URI转换为String,仅占用主机,端口和路径

时间:2016-01-06 17:36:42

标签: java string uri

我有java.net.URI类型的对象,我想将其转换为String表示,但我只对以下组件感兴趣:

  • 宿主
  • 端口
  • 路径

我不想拥有查询,片段,用户信息或方案等任何其他元素。

getHost()getPort()getPath()手动执行此操作看起来像一个脆弱的解决方案。是否有URI格式化程序或自定义toString可用?

脆弱的我在这里意味着可能会有一些我会忘记手动处理的角落情况。像例如主机是IPv6地址然后是needs to have brackets

的情况

1 个答案:

答案 0 :(得分:4)

您可以相当轻松地构建新URI:

@app.route('/question/<topic_id>', methods=['GET', 'POST'])
def newquestion(topic_id):
    username = 'elena27'  
    question_ = request.form['question']
    new_question = applicativo.newQuestion(username, question_, topic_id)
    db.session.add(new_question)
    db.session.commit()
    db.session.remove()
    return render_template('newquestion.html')

你可能想要验证主机是非空的,以便它是明智的。

或者,连接方法实际上不太可能复杂得多 - 我假设您将进行单元测试以检查所有组合,无论实现如何。